<template>
  <div>
    <!-- 美食信息 -->
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/ManageHome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      <el-breadcrumb-item>美食店面信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!--    功能区-->
        <div style="margin: 10px 0">
          <!--    搜索区-->
          <div style="margin: 10px 0">
            <span style="font-weight:700;">店面名称</span>
            <el-input v-model="searchFood" clearable placeholder="请输入商品名称" prefix-icon="el-icon-search" style="margin-left:5px;width: 150px" />
            <span style="font-weight:700; margin-left:10px;">标签</span>
            <el-input v-model="searchTips" clearable placeholder="请输入标签" prefix-icon="el-icon-search" style="margin-left:5px;width:150px" />
           
            <el-button icon="el-icon-search" @click="load"
              style="background-color: #143371;margin-left:410px; color: aliceblue;">搜索</el-button>
            <el-button icon="el-icon-refresh-left" style="margin-left:10px;background-color: #143371; color: aliceblue;"
              @click="reset">重置</el-button>
              
              <download-excel style="display: inline;"
                class="export-excel-wrapper"
                :data="tableData"
                :fields="json_fields"
                type="xls"
                worksheet="My Worksheet"
                name="美食信息"
    >
      <el-button style="background-color: #143371; color: aliceblue;"
       >导出</el-button>
    </download-excel>
            
            <div style="float: right">

              <el-tooltip content="添加美食店面" placement="top">

                <el-button style="background-color: #143371; color: aliceblue;width: 40px;" icon="el-icon-plus"
                  @click="add"></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
        <!--    表格-->
        <el-table v-loading="loading" :data="tableData" max-height="1000" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="店面名称">
                  <span>{{ props.row.foodName }}</span>
                </el-form-item>
              
                <el-form-item label="店面地址">
                  <span>{{ props.row.foodAddress }}</span>
                </el-form-item>
                <el-form-item label="店面标签">
                  <span>{{ props.row.foodTips }}</span>
                </el-form-item>
                <el-form-item label="店面电话">
                  <span>{{ props.row.foodPhone }}</span>
                </el-form-item>
                
                <el-form-item label="店面封面">
                  <img :src="props.row.foodCoverImg" alt="" style="width: 180px; height: 150px;">
                </el-form-item>
                <el-form-item label="更多图片">
                  <div style="display: flex;">
                    <img :src="item" alt="" v-for="(item, index) in props.row.imgs"
                      :key="index" style="width: 180px; height: 150px;">
                  </div>
                </el-form-item>
                <el-form-item label="店面概要">
                  <p>{{ props.row.foodContent }}</p>
                </el-form-item>

              </el-form>
            </template>
          </el-table-column>


          <el-table-column label="#" type="index" fixed />
          <el-table-column label="编号" prop="foodId" sortable width="100" />
          <el-table-column label="名称" prop="foodName" width="180px" />
          <el-table-column label="地址" prop="foodAddress" width="150px" />
          <el-table-column label="标签" prop="foodTips" width="120px" />
          <el-table-column label="服务时间" prop="foodTime" width="120px" />
          <el-table-column label="电话" prop="foodPhone" width="120px" />
          <el-table-column v-if="false" label="内容" prop="foodContent"  width="240px" />
          <el-table-column label="浏览量" prop="visits" sortable width="120px" />
          <el-table-column label="评分" prop="score" sortable width="120px" />
          <el-table-column label="距离" prop="distant" sortable width="120px" />
          <!--      操作栏-->
          <el-table-column label="操作" width="150px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div style="margin: 10px 0">
          <el-pagination :currentPage="currentPage" :page-size="pageSize" :page-sizes="[10, 20]" :total="total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
        </div>
        <div>
          <!--      弹窗-->
          <el-dialog :visible.sync="dialogVisible" title="操作" width="50%" @close="cancel" top="30px">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">

              <el-form-item label="名称" prop="foodName">
                <el-input v-model="form.foodName" style="width: 80%" placeholder="店面的名字"></el-input>
              </el-form-item>

            
              <el-form-item label="地址" prop="foodAddress">
                <el-input v-model="form.foodAddress" style="width: 80%" placeholder=""></el-input>
              </el-form-item>

              <el-form-item label="标签" prop="foodTips">
                <el-input v-model.number="form.foodTips" style="width: 80%" placeholder=""></el-input>
              </el-form-item>

              <el-form-item label="服务时间" prop="foodTime">
                <el-input v-model="form.foodTime" style="width: 80%" placeholder=""></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="foodPhone">
                <el-input v-model="form.foodPhone" style="width: 80%" placeholder=""></el-input>
              </el-form-item>
              
              <el-form-item label="封面图" prop="goodsPic">
                <el-upload action="" list-type="picture-card" :limit="1" :on-preview="handlePictureCoverPreview"
                  :on-remove="handleCoverRemove" accept=".jpg,.png" :on-exceed="handleExceed" :file-list="cover_list"
                  :http-request="UploadCover">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="CoverdialogVisible">
                  <img width="100%" :src="CoverdialogImageUrl" alt="">
                </el-dialog>

              </el-form-item>
              <el-form-item label="更多图片(最多9张)" prop="imgs">
                <el-upload action="" list-type="picture-card" :limit="9" :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove" accept=".jpg,.png" :on-exceed="handleNineExceed" :auto-upload="true"
                  :file-list="more_list" :http-request="UploadMore" multiple>
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="MoredialogVisible">
                  <img width="100%" :src="MoredialogImageUrl" alt="">
                </el-dialog>

              </el-form-item>


              <el-form-item label="描述">
                      <el-input
                type="textarea"
                autosize
                placeholder="请输入内容"
                v-model="form.foodContent">
              </el-input>

              </el-form-item>

            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import request from '@/utils/request'
export default {
  name: "SceneryInfo",
  data() {
    // 时间检验
    const checkScTime = (rule,value,callback) =>{
      const s = value.split("-")
      const p =/^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/
      if(s.length!=2){
        return callback(new Error("时间格式不正确"));
      }
      if(!p.test(s[0])||!p.test(s[1])){
        return callback(new Error("时间格式不正确"));
      }
      const st = s[0].split(":")
      const ed = s[1].split(":")
      var stt = st[0]+st[1];
      var edd = ed[0]+ed[1];
      console.log("sta",stt)
      console.log("end",edd)
      if(parseInt(stt)>=parseInt(edd)){
        return callback(new Error("时间格式不正确"));
      }
      callback()
    };
    // 电话校验
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    // const fieldName = ["店面ID", "店面图片", "店面名称","店面地址","店面标签","店面服务时间","店面电话","店面内容","店面访问量","店面评分","店面距离"];
    // const filterVal = ["foodId", "foodCoverImg", "foodName","foodaddress","foodTips","foodTime","foodPhone","visit","score","distant"];
    return {
      json_fields:{
        店面ID:'foodId',
        店面名称:'foodName',
        店面地址:"foodaddress",
        店面标签:'foodTips',
        店面服务时间:'foodTime',
        店面电话:"foodPhone",
        店面内容:"foodContent",
        店面访问量:"visit",
        店面评分:"score",
      },
      loading: true,
      editJudge: true,
      judge: false,
      dialogVisible: false,
      searchFood: "",
      searchTips:"",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogloading: false,
      cover_list: [],
      more_list: [],
      CoverdialogImageUrl: '',
      CoverImageUrl:'',
      moreImageUrl:[],
      CoverdialogVisible: false,
      MoredialogImageUrl: '',
      MoredialogVisible: false,
      // 表格数据模型
      tableData: [
        {
          foodId:1,
          foodCoverImg:'lhs4.jpg',
          foodName:'沙县小吃',
          foodAddress:'南昌大学软件学院一食堂',
          foodTips:'正宗味道',
          foodTime:'9:00-19:00',
          foodPhone:'8008008820',
          foodContent:'全南昌最正宗的沙县小吃，绝无仅有的美味，只有青山湖大专的学生才有机会品尝',
          visit:5623,
          score:4.7,
          distant:0.2,
          imgs:[]
        }
      ],
      form: {

        foodId:1,
          foodCoverImg:'',
          foodName:'沙县小吃',
          foodAddress:'南昌大学软件学院一食堂',
          foodTips:'正宗味道',
          foodTime:'9:00-19:00',
          foodPhone:'8008008820',
          foodContent:'全南昌最正宗的沙县小吃，绝无仅有的美味，只有青山湖大专的学生才有机会品尝',
          visit:5623,
          score:4.7,
          distant:0.2,
          imgs:[],

      },
      // 表单验证规则
      rules: {
        foodName: [
          { required: true, message: "请输入门店名称", trigger: "blur" },
          { validator:function(rule,value,callback){
                          if(/^[\u4e00-\u9fa5]{0,}$/.test(value) == false){
                              callback(new Error("请输入中文"));
                          }else{
                              //校验通过
                              callback();
                          }
                        }, trigger: 'blur'}
        ],
        foodaddress: [
          { required: true, message: "请输入门店地址", trigger: "blur" },
          { validator:function(rule,value,callback){
                          if(/^.+$/.test(value) == false){
                              callback(new Error("请输入内容"));
                          }else{
                              //校验通过
                              callback();
                          }
                        }, trigger: 'blur'}
        ],
        foodTips: [
          { required: true, message: "请输入标签", trigger: "blur" }
        ],
        foodTime: [{ required: true, message:"请输入服务时间",validator:checkScTime, trigger: "blur" }],
        foodPhone: [{ required: true, message:"请输入门店电话", trigger: "blur" },
        { validator:function(rule,value,callback){
                          if(/^[0-9]*$/.test(value) == false){
                              callback(new Error("请输入数字"));
                          }else{
                              //校验通过
                              callback();
                          }
                        }, trigger: 'blur'}
      ],
      },
      editDisplay: {
        display: "block",
      },
      display: {
        display: "none",
      },
    };
  },
  created() {
    this.load();
    this.loading = true;
    setTimeout(() => {
      //设置延迟执行
      this.loading = false;
    }, 1000);
  },
  methods: {

    cancel() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.cover_list=[]
      this.more_list=[]
      this.CoverdialogImageUrl=''
      this.MoredialogImageUrl=''
      this.coverImageUrl=''
      this.moreImageUrl=''
    },
    UploadCover(data){
      var formData = new FormData()
      formData.append('type','food')
      formData.append('file',data.file)
      this.dialogloading = true;
      console.log("图片文件",data)
      console.log("现在的图片",this.cover_list)
      request.post("/scenery/upload",formData).then(res=>{
        if(res.code==='1'){
          this.cover_list = []
          this.coverImageUrl = res.data,
          this.cover_list.push({name:data.file.name,url:res.data})
          this.dialogloading = false;
        }else{
          this.dialogloading = false
          this.$message({
            type:'error',
            message:'上传失败'
          })
        }
      
      })

      
      
    },
    UploadMore(data){
      var formData = new FormData()
      formData.append('type','food')
      formData.append('file',data.file)
      this.dialogloading = true;
      console.log("上传详细图片",data)
      console.log("现在的图片",this.moreImageUrl)
      request.post("/scenery/upload",formData).then(res=>{
        if(res.code==='1'){
         // this.cover_list = []
         this.moreImageUrl.push(res.data)
         console.log("更多图片为：")
         console.log(this.moreImageUrl)
          this.more_list.push({name:data.file.name,url:res.data})
          this.dialogloading = false;
        }else{
          this.dialogloading = false
          this.$message({
            type:'error',
            message:'上传失败'
          })
        }
      
      })
    },
    handleRemove(file,fileList) {
      console.log("删除",file);
      this.more_list = this.more_list.filter(item=>{
        return item.name!=file.name
      })
      
    },
    handleCoverRemove(file,fileList){
      console.log("删除",file);
      this.cover_list = []
    },
    handlePictureCoverPreview(file){
      this.CoverdialogImageUrl = file.url;
      this.CoverdialogVisible = true;
    },
    handlePictureCardPreview(file) {
      this.MoredialogImageUrl = file.url
      this.MoredialogVisible = true
    },

    handleExceed(){
      this.$message.warning(`只允许上传一张图片`);
    },
    handleNineExceed(){
      this.$message.warning(`只允许上传9张图片`);
    },
    async load() {
      request.get("/food/findlist", {
            params: {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                searchFood: this.searchFood,
                searchTips:this.searchTips,
            },
        }).then((res) => {
            console.log(res);
            this.tableData = res.data.foodList;
            this.total = res.data.total;
            this.loading = false;
        });
    },
    reset() {
      // 重置筛选条件
      request.get("/food/reset", {
          params: {
              pageNum: 1,
              pageSize: this.pageSize,
              
          },
      }).then((res) => {
          console.log(res);
          this.tableData = res.data.foodList;
          this.total = res.data.total;
          this.loading = false;
      });
    },
    handleDelete(index, row) {
      // 确认框确认是否要删除
      this.$confirm("确定要删除" + row.foodId + "的信息吗?", "删除提示", {
        iconClass: "el-icon-question", //自定义图标样式
        confirmButtonText: "残忍删除", //确认按钮文字
        cancelButtonText: "取消删除", //取消按钮文字
        showClose: true, //是否显示右上角关闭按钮
        type: "warning", //提示类型  success/info/warning/error
      }).then(() => {  //选择确认按钮进入此方法
        var temp={
          foodId:row.foodId
        }
        request.delete("/food/delete",{params:temp}).then(res => {
          console.log(row.foodId)
          if (res.code === "1") {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.load()
          }
          else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })
      }).catch(() => { //选择取消按钮进入此方法
        //取消操作
        alert('取消')
      });
    },
    handleEdit(index, row) {
      this.judge = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form = JSON.parse(JSON.stringify(row));
        this.cover_list.push({name:"foods",url:this.form.foodCoverImg})
        this.more_list = []
       for(var i =0;i<this.form.imgs.length;i++){
         this.more_list.push({name:'food'+i,url:this.form.imgs[i]})
       }
        this.editDisplay = { display: "block" };
      });
    },

    save() {
      this.$refs.form.validate(vaild => {
        if (vaild) {
          if (this.judge) {
            //先表单验证，再放put请求
            this.form.foodCoverImg = this.cover_list[0].url
            this.form.imgs = []
            for(var i=0;i<this.more_list.length;i++){
              
              this.form.imgs.push(this.more_list[i].url)
             
            }

            
            // this.form.imgs = this.more_list
            console.log(this.form.imgs)
            request.put("/food/update", this.form).then(res => {
              if (res.code === "1") {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.search = "",
                this.load();
                this.dialogVisible = false
                this.more_list = []

              }
              else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })


          }
          else {
            //发post请求
            this.form.foodCoverImg = this.cover_list[0].url
            this.form.imgs = []
            for(var i=0;i<this.more_list.length;i++){
              
              this.form.imgs.push(this.more_list[i].url)
             
            }
            request.post("/food/add", this.form).then(res => {
              if (res.code === "1") {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.search = "",
                  this.load();
                this.dialogVisible = false
              }
              else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })
          }
          this.cancel();
        }
      })


    },
    // export2Excel() {
    //   require.ensure([], () => {
    //     const { export_json_to_excel } = require("@/excel/Export2Excel");
    //     const fieldName = ["店面ID", "店面图片", "店面名称","店面地址","店面标签","店面服务时间","店面电话","店面内容","店面访问量","店面评分","店面距离"];
    //     const filterVal = ["foodId", "foodCoverImg", "foodName","foodaddress","foodTips","foodTime","foodPhone","visit","score","distant"];
    //     const data = this.tableData.map(v => filterVal.map(j => v[j]));
    //     export_json_to_excel(fieldName, data, "美食店面列表");
    //   });
    // },
  
    add() {
      this.dialogVisible = true;
      this.judge = false;
      this.form = {}
    },
    handleSizeChange(pageSize) {
      //改变每页个数
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      //改变页码
      this.currentPage = pageNum;
      this.load();
    },

  }


}
</script>
<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
  display: block;
}
.el-upload-list__item {
  transition: none !important;
}
</style>